package com.tec.security.utils.captcha;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CaptchaRedisServiceImpl implements CaptchaRedisService {
    private final RedisTemplate<String,String> redisTemplate;
    @Autowired
    public CaptchaRedisServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean setCaptcha(String key, String code) {
        try{
            redisTemplate.opsForValue().set("captcha:"+key, code,10, TimeUnit.MINUTES);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public String getCaptcha(String key) {
        try{
            String temp= redisTemplate.opsForValue().get("captcha:"+key);
            if(temp==null){
                return "select key null";
            }else {
                return temp;
            }
        }catch (Exception e){
            return "select key error";
        }
    }

    @Override
    public void deleted(String key) {
        try{
            redisTemplate.delete("captcha:"+key);
        }catch (Exception ignored){

        }
    }
}
